package servlet.rool;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import service.AdminService;
import service.impl.AdminServiceImpl;
import util.JsonDateValueProcessor;
import util.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 后台用户分页的servlet
 */
@WebServlet(value = "/AdminPageServlet")
public class AdminPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置返回给页面的格式
        response.setContentType("text/json;charset=UTF-8");
        PageBean pb=new PageBean();
        String pageIndex=request.getParameter("page");//当前页面显示的索引
        if(null==pageIndex){
            pb.setPageIndex(1);
        }else {
            pb.setPageIndex(Integer.parseInt(pageIndex));
        }
        String pageSize=request.getParameter("limit");//设置每页显示的数据条数
        if(null==pageSize){
            pb.setPageSize(2);
        }else {
            pb.setPageSize(Integer.parseInt(pageSize));
        }
        AdminService as=new AdminServiceImpl();
        //获取组合查询的名称参数
        String ename=request.getParameter("name");
        //获取组合查询的账号参数
        String account=request.getParameter("account");
        //调用service层的分页方法
        pb=as.adminPageList(pb,ename,account);
        //创建json对象
        JSONObject json=new JSONObject();
        json.put("code",0);//状态码
        json.put("msg","");//附带消息
        json.put("count",pb.getTotalCount());//总记录数，用于layui计算页数
        //把list转换成json数组
        JsonConfig config=new JsonConfig();
        //解决集合里有日期，然后转换成json字符串报错
        config.registerJsonValueProcessor(java.util.Date.class,new JsonDateValueProcessor());
        JSONArray array= JSONArray.fromObject(pb.getList(),config);
        json.put("data",array);
        PrintWriter out=response.getWriter();
        out.print(json);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        doGet(request, response);
    }
}
